package com.huawang.mdesign.model.service.util;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.nio.file.Files;
import java.util.Objects;

/**
 * 文件读写工具类
 *
 * @author cdl
 */
public class FileUtil {

    private FileUtil() {}

    @SneakyThrows
    @NotNull
    public static String readFile(File file) {
        if (Objects.isNull(file) || !file.exists()) {
            return "";
        }

        try (BufferedReader br = Files.newBufferedReader(file.toPath())) {
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }

            if (builder.length() > 0) {
                return builder.toString();
            }
        }
        return "";
    }

    @SneakyThrows
    public static void writeFile(File file, Object data) {
        Assert.isTrue(Objects.nonNull(file) && file.exists());
        if (Objects.nonNull(file) && file.exists()) {
            try (BufferedWriter writer = Files.newBufferedWriter(file.toPath())) {
                writer.write(JSONUtil.toJsonStr(data));
            }
        }
    }
}
